<template>
  <div class="vehicle-list">
    <el-card>
      <!-- <template #header>
        <div class="flex justify-between items-center">
          <span class="font-medium">车辆列表</span>
          <el-button type="primary" :icon="CirclePlus" @click="openVehicleForm('新增车辆')">
            新增车辆
          </el-button>
        </div>
      </template> -->
      
      <ProTable
        ref="proTableRef"
        :columns="columns"
        :search-columns="searchColumns"
        :request-api="getTableList"
        :init-param="{ fleetId: fleetId }"
        row-key="id"
      >
        <template #operation="{ row }">
          <el-button
            type="primary"
            link
            :icon="View"
            @click="viewTransportDetails(row)"
          >
            查看详情
          </el-button>
          <!-- <el-button
            type="primary"
            link
            :icon="EditPen"
            @click="openVehicleForm('编辑车辆', row)"
          >
            编辑
          </el-button>
          <el-button
            type="primary"
            link
            :icon="Delete"
            @click="deleteVehicle(row)"
          >
            删除
          </el-button> -->
        </template>
      </ProTable>
    </el-card>
    
    <!-- 车辆表单 -->
    <VehicleForm ref="vehicleFormRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { CirclePlus, EditPen, Delete, View } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
import ProTable from '@/components/ProTable/index.vue';
import VehicleForm from '@/views/dept/deptList/components/VehicleForm.vue';
import { getVehiclesByDeptIdApi } from '@/api/modules/dtuinfo/dtuFtpInfo';
import type { ColumnProps, ProTableInstance, SearchProps } from '@/components/ProTable/interface';
import type { DtuFtpInfoQuery, DtuFtpInfoRow } from '@/api/types/dtuinfo/dtuFtpInfo';

defineOptions({
  name: 'VehicleList'
});

// Define props
const props = defineProps<{
  fleetId?: number;
}>();

const route = useRoute();
const router = useRouter();

// Use prop value if provided, otherwise get from route
const fleetId = ref<number>(props.fleetId || (route.query.fleetId ? Number(route.query.fleetId) : 0));

const proTableRef = ref<ProTableInstance>();
const vehicleFormRef = ref<InstanceType<typeof VehicleForm>>();

// 表格配置项
const columns: ColumnProps<DtuFtpInfoRow>[] = [
  { prop: 'deviceId', label: '设备ID', width: 150 },
  { prop: 'remoteIp', label: '远程IP', width: 150 },
  { prop: 'remotePort', label: '远程端口', width: 120 },
  // { prop: 'channelId', label: '通道ID', width: 120 },
  // { prop: 'status', label: '状态', width: 100 },
  // { prop: 'connectTime', label: '连接时间', width: 180 },
  { prop: 'createTime', label: '创建时间' },
  // { prop: 'updateTime', label: '更新时间', width: 180 },
  { prop: 'operation', label: '操作', fixed: 'right', width: 180 }
];

// 搜索条件项
const searchColumns = ref<SearchProps[]>([
  { prop: 'deviceId', label: '设备ID', el: 'input' },
  // { 
  //   prop: 'status', 
  //   label: '状态', 
  //   el: 'select',
  //   enum: [
  //     { label: '已连接', value: 1 },
  //     { label: '未连接', value: 0 }
  //   ]
  // }
]);

// 获取表格列表
const getTableList = (params: DtuFtpInfoQuery) => {
  if (fleetId.value && fleetId.value > 0) {
    return getVehiclesByDeptIdApi(fleetId.value, params);
  }
  // 如果没有有效的fleetId，返回空数据
  return Promise.resolve({
    data: {
      current: 1,
      limit: 10,
      totalPage: 0,
      total: 0,
      rows: []
    }
  });
};

// 打开车辆表单（新增/编辑）
const openVehicleForm = (title: string, row: any = {}) => {
  const params = {
    title,
    row: { ...row },
    fleetId: fleetId.value,
    getTableList: proTableRef.value?.getTableList
  };
  vehicleFormRef.value?.acceptParams(params);
};

// 删除车辆
const deleteVehicle = async (row: any) => {
  ElMessageBox.confirm(`确定要删除车辆【${row.deviceId}】吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      // 这里应该调用实际的删除API
      console.log('删除车辆:', row.id);
      proTableRef.value?.getTableList();
    } catch (error) {
      console.error('删除车辆失败:', error);
    }
  }).catch(() => {
    // 取消删除
  });
};

// 查看运输详情
const viewTransportDetails = (row: DtuFtpInfoRow) => {
  router.push({
    name: 'TransportList',
    query: { deviceId: row.deviceId }
  });
};

// 监听路由变化和prop变化
watch(() => [route.query.fleetId, props.fleetId], ([routeFleetId, propFleetId]) => {
  if (propFleetId !== undefined) {
    fleetId.value = Number(propFleetId);
  } else if (routeFleetId) {
    fleetId.value = Number(routeFleetId);
  }
  
  if (proTableRef.value && fleetId.value > 0) {
    proTableRef.value.searchParam.fleetId = fleetId.value;
    proTableRef.value.getTableList();
  }
}, { immediate: true });
</script>

<style scoped lang="scss">
.vehicle-list {
  padding: 20px;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.font-medium {
  font-weight: 500;
}
</style>